﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Game.Foundation;
using Bruce.Net;

namespace Server.Major
{
    /// <summary>
    /// 游戏服务器
    /// </summary>
    class GameServerDispatcher : AbsDispatcher<IPacket>
    {
        protected override void Handle(IPacket item)
        {
            Packet packet = (Packet)item;
            packet.Flip();
            PacketType type = (PacketType)packet.Protocol;

            switch (type)
            {
                case PacketType.Pong:
                    //this.OverdueTime = DateTime.Now.AddSeconds(ActiveSeconds);
                    break;

                case PacketType.注册游戏处理程序:
                    ProcessRegisterGameServer(packet);
                    break;

                case PacketType.注销游戏处理程序:
                    ProcessLogoutGameServer(packet);
                    break;
                default:
                    Console.WriteLine("未找到对应的游戏服协议。");
                    break;
            }
        }

        private void ProcessRegisterGameServer(Packet packet)
        {
            GameConfig game = new GameConfig();
            game.Name = packet.ReadString();
            game.IPAddress = packet.ReadString();
            game.Port = packet.ReadInt32();
            game.SeatCount = packet.ReadInt32();
            game.RelativePath = packet.ReadString();
            game.DownloadPath = packet.ReadString();
            int areaCount = packet.ReadInt32();
            for (int i = 0; i < areaCount; i++)
            {
                GameAreaConfig area = new GameAreaConfig();
                area.ID = packet.ReadInt32();
                area.Name = packet.ReadString();
                int roomCount = packet.ReadInt32();

                for (int j = 0; j < roomCount; j++)
                {
                    GameRoomConfig room = new GameRoomConfig();
                    room.ID = packet.ReadInt32();
                    room.Name = packet.ReadString();

                    area.RoomList.Add(room);
                }

                game.AreaList.Add(area);
            }


            Console.WriteLine("游戏[{0}]在[{1}:{2}]上启动.", game.Name, game.IPAddress, game.Port);
            packet.SetRelationData<GameConfig>(game);
            Program.m_gameDict[game.Name] = game;

        }

        private void ProcessLogoutGameServer(Packet p)
        {
            string name = p.ReadString();
            if (Program.m_gameDict.ContainsKey(name))
            {
                Program.m_gameDict.Remove(name);
                Console.WriteLine("游戏[{0}]已关闭.", name);
            }
        }
    }
}
